/*
 * Copyright 2010 Original Author(s)
 * 
 * This file is part of Kommando
 * 
 * Kommando is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Kommando is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Kommando.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.kommando.application.win32;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.kommando.core.util.Assert;
import org.kommando.filesystem.win32.LnkParser;

/**
 * Helper class for working with {@link Win32Application}s.
 * 
 * @author Peter De Bruycker
 */
public class Win32ApplicationContext {

    private String isApplicationRunningPath;
    private String closeApplicationPath;

    public Win32ApplicationContext(String isApplicationRunningPath, String closeApplicationPath) {
        Assert.argumentNotEmpty("isApplicationRunningPath", isApplicationRunningPath);
        Assert.argumentNotEmpty("closeApplicationPath", closeApplicationPath);

        this.isApplicationRunningPath = isApplicationRunningPath;
        this.closeApplicationPath = closeApplicationPath;
    }

    public void exit(File applicationFile) throws IOException {
        String name = getRealFilename(applicationFile);

        new ProcessBuilder(System.getenv("comspec"), "/c", closeApplicationPath, name, "|", "find", "/V", "\"\"").start();
    }

    public boolean isOpen(File applicationFile) throws IOException {
        String name = getRealFilename(applicationFile);

        Process process = new ProcessBuilder(System.getenv("comspec"), "/c", isApplicationRunningPath, name, "|", "find", "/V", "\"\"").start();

        InputStream in = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        String line = reader.readLine();
        reader.close();

        if (line != null) {
            return line == null ? false : !line.equals("-1");
        }

        return false;
    }

    private String getRealFilename(File file) throws IOException {
        String name = file.getName();
        if (file.getName().endsWith(".lnk")) {
            LnkParser parser = new LnkParser(file);
            name = new File(parser.getRealFilename()).getName();
        }

        return name;
    }

}
